const { parseString } = require("xml2js")
const fs = require("fs")
const path = require("path")

module.exports = {
    getUserDataAsync(req) {
        return new Promise((resolve, reject) => {
            let xmlData = ""
            req.on("data", data => {
                xmlData += data.toString()
            }).on("end", () => {
                resolve(xmlData)
            })
        })
    },

    parseXMLAsync(xmlData) {
        return new Promise((resolve, reject) => {
            parseString(xmlData, { trim: true }, (err, data) => {
                if (!err) {
                    resolve(data)
                } else {
                    reject("parseXml fail" + err)
                }
            })
        })
    },

    formatMessage(jsonData) {
        return new Promise((resolve, reject) => {
            let message = {}
            jsonData = jsonData.xml
            if (typeof jsonData === "object") {
                for (let key in jsonData) {
                    let value = jsonData[key]
                    if (Array.isArray(value) && value.length > 0) {
                        message[key] = value[0]
                    }
                }
            }
            resolve(message);
        })
    },

    writeFileAsync(data, filename) {
        data = JSON.stringify(data)
        filename = path.resolve(__dirname + '/../saveTempFile', filename)
        return new Promise((resolve, reject) => {
            fs.writeFile(filename, data, err => {
                if (!err) {
                    console.log("文件保存成功。")
                    resolve()
                } else {
                    console.log("文件保存失败。")
                    reject("saveTicket fail" + err)
                }
            })
        })
    },

    readFileAsync(filename) {
        filename = path.resolve(__dirname + '/../saveTempFile', filename)
        return new Promise((resolve, reject) => {
            fs.readFile(filename, (err, data) => {
                if (!err) {
                    resolve(JSON.parse(data))
                } else {
                    reject("readFile fail." + err)
                }
            })
        })
    }
}



/**
 * 收到用户发来的数据流
 * <xml><ToUserName><![CDATA[gh_96337ebb5259]]></ToUserName>
    <FromUserName><![CDATA[oPBuf6haO1mR_ASkIFsWdLxobmSE]]></FromUserName>
    <CreateTime>1653204197</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[1]]></Content>
    <MsgId>23668191172387111</MsgId>
    </xml>
 */



/**
 * 解析用户发来的数据流
 * {
  xml: {
    ToUserName: [ 'gh_96337ebb5259' ],
    FromUserName: [ 'oPBuf6haO1mR_ASkIFsWdLxobmSE' ],
    CreateTime: [ '1653204352' ],
    MsgType: [ 'text' ],
    Content: [ '1' ],
    MsgId: [ '23668198150297714' ]
  }
}
 */


/**
 * 格式化数据
 * {
  ToUserName: 'gh_96337ebb5259',
  FromUserName: 'oPBuf6haO1mR_ASkIFsWdLxobmSE',
  CreateTime: '1653204668',
  MsgType: 'text',
  Content: '1',
  MsgId: '23668199763716664'
}
 */